package com.yl.androidutilscenter.http

import com.yl.androidutilscenter.utils.LogUtils
import com.yl.androidutilscenter.utils.ext.getFlow
import com.yl.androidutilscenter.utils.ext.getFlows
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach

//import me.jessyan.retrofiturlmanager.RetrofitUrlManager

/**
 * @author
 * @description: 动态切换baseUrl
 * @date :2024/3/14
 * @version 1.0.0
 */


/**
 * 协程作用域中发送请求
 */
fun <T> CoroutineScope.sendRequest(
    requestBlock: suspend () -> T,
    errorCallBack: ((error: Throwable) -> Unit)? = null,
    callback: (T) -> Unit
) {
    getFlow { requestBlock() }
        .catch {
            it.printStackTrace()
            errorCallBack?.let { it1 -> it1(it) }
            LogUtils.i("请求发生异常：${it.message}")
        }.onEach {
            callback(it)
        }.launchIn(this)
        .start()
}


fun <T> CoroutineScope.sendRequests(
    vararg requestBlocks: suspend () -> T,
    errorCallBack: ((error: Throwable) -> Unit)? = null,
    callback: (T) -> Unit
) {
    getFlows(*requestBlocks)
        .catch {
            it.printStackTrace()
            errorCallBack?.let { it1 -> it1(it) }
            LogUtils.i("请求发生异常：${it.message}")
        }.onEach {
            callback(it)
        }.launchIn(this)
        .start()
}










